package com.situ.day25;

import org.junit.Test;

public class Search {

    public static void main(String[] args) {
        int[] array = new int[] { 8, 17, 19, 37, 40, 73, 79, 82, 87, 95, 97, 98 };
        int target = 95;
        // 找到了返回索引位置，找不到返回-1
        int index = binarySearch(array, target);
        System.out.println(index);

        String name = Thread.currentThread().getName();
        System.out.println(name);//main

        //开启一个进程，一个进程里面有多个线程，真正干活的是进程里面的线程。
        //默认启动一个主线程
    }

    private static int binarySearch(int[] array, int target) {
        int low = 0;
        int high = array.length - 1;
        int mid = (low + high) / 2;
        while (low <= high) {
            if (target == array[mid]) {
                return mid;
            }

            if (target > array[mid]) {
                low = mid + 1;
            } else if (target < array[mid]) {
                high = mid - 1;
            } /*else {
                return mid;
            }*/
            mid = (low + high) / 2;
        }

        //执行到这里代表没有找到，low > high
        return -1;
    }

    @Test
    public void test2() {
        int[] array = new int[] { 8, 17, 19, 37, 40, 73, 79, 82, 87, 95, 97, 98 };
        int target = 95;
        int low = 0;
        int high = array.length - 1;
        // 找到了返回索引位置，找不到返回-1
        int index = binarySearch2(array, target, low ,high);
        System.out.println(index);
    }

    private int binarySearch2(int[] array, int target, int low, int high) {
        System.out.println("low: " + low);
        System.out.println("high: " + high);
        if (low > high) {
            return -1;
        }

        int mid = (low + high) / 2;
        if (target > array[mid]) {
            return binarySearch2(array, target, mid + 1, high);
        } else if (target < array[mid]) {
            return binarySearch2(array, target, low, mid - 1);
        } else {
            return mid;
        }
    }
}
